package org.example;

public class Test2 {
    //leetcode 416 分隔等和字符串 https://leetcode.cn/problems/partition-equal-subset-sum/description/
    public boolean canPartition(int[] nums) {
        int sum = 0, n = nums.length;
        for (int num : nums) sum += num;
        if (sum %2 == 1) return false;
        sum /= 2;
        int[][] dp = new int[n+1][sum+1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= sum; j++) {
                dp[i][j] = dp[i-1][j];
                if (j >= nums[i-1]) {
                    dp[i][j] = Math.max(dp[i][j],dp[i-1][j-nums[i-1]] + nums[i-1]);
                }
            }
        }
        return dp[n][sum] == sum;
    }

    //空间优化
    public boolean canPartition1(int[] nums) {
        int sum = 0, n = nums.length;
        for (int num : nums) sum += num;
        if (sum %2 == 1) return false;
        sum /= 2;
        int[] dp = new int[sum+1];
        for (int i = 1; i <= n; i++) {
            for (int j = sum; j >= nums[i-1]; j--) {
                dp[j] = Math.max(dp[j],dp[j-nums[i-1]] + nums[i-1]);
            }
            if (dp[sum] == sum) return true; //剪枝操作
        }
        return dp[sum] == sum;
    }
}
